<template>
  <el-dialog :model-value="isShow" title="分配角色" @close="emit('close')">
    <el-select
      v-model="list"
      multiple
      placeholder="Select"
      style="width: 240px;"
    >
      <el-option
        v-for="item in options"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="emit('close')">取消</el-button>
        <el-button type="primary" @click="submit">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ApiGetAllUserList, ApiGetUserRole, ApiSetRole } from './api'
import { ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
const props = defineProps({
  isShow: {
    type: Boolean,
    default: false,
  },
  id: {
    type: Number,
    default: 0,
  },
})
const emit = defineEmits(['close'])

const list = ref<number[]>([])

const options = ref<{ value: number; label: string }[]>([])

// 获取全部角色列表
ApiGetAllUserList().then((res) => {
  if (res.code === 200) {
    options.value = res.data.map((item) => ({
      value: item.id,
      label: item.name,
    }))
  }
})

// 监听id变化，发起请求
watch(
  () => props.id,
  () => {
    if (props.id === 0) return
    // 获取原本的角色
    ApiGetUserRole(props.id).then((res) => {
      if (res.code === 200) {
        list.value = res.data.map((item) => item.id)
      }
    })
  },
)

// 确认按钮
const submit = () => {
  ElMessageBox.confirm('此操作将修改当前用户角色, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      ApiSetRole(props.id, list.value).then((res) => {
        if (res.code === 200) {
          ElMessage.success('👍分配成功！')
          emit('close')
        } else {
          ElMessage.error('😩分配失败！')
        }
      })
    })
    .catch(() => {
      ElMessage.warning('☺️您已取消！')
    })
}
</script>
<style lang="less" scoped></style>
